﻿using Consul.AspNetCore;
using Consul;
using DeZhen.Core.Consul.Entity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
using DeZhen.Core.Framework.Config;
using DeZhen.Core.Consul.Platform;
using Microsoft.Extensions.Options;
using System.Timers;

namespace DeZhen.Core.Consul.Service
{
    public class RegisterPlatform
    {
        private IConsulClient _consulClient;
        private AgentServiceRegistration agentServiceRegistration;
        private AgentServiceCheck httpCheck;
        private Timer timer;
        public void InitializeRegisterConsulConfig()
        {
            ConsulConfig config = AppConfig.GetSection("Consul").Get<ConsulConfig>();
            if (config == null)
            {
                return;
            }
            if (String.IsNullOrEmpty(config.GatewayAddress))
            {
                StartConfig httpInfo = AppConfig.GetSection("StartConfig").Get<StartConfig>();
                config.GatewayAddress = $"http://{httpInfo.Ip}:{httpInfo.Port}";
            }
            if (config.GatewayAddress.Substring(config.GatewayAddress.Length - 1, 1) != "/")
            {
                config.GatewayAddress = config.GatewayAddress + "/";
            }
            _consulClient = new ConsulClient(consul =>
            {
                consul.Address = new Uri($"http://{config.ConsulIP}:{config.ConsulPort}");
            });
            agentServiceRegistration = new AgentServiceRegistration();
            httpCheck = new AgentServiceCheck()
            {
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),
                Interval = TimeSpan.FromSeconds(10),
                HTTP = config.GatewayAddress + "api/consul/health",
                Timeout = TimeSpan.FromSeconds(5)
            };
            agentServiceRegistration.Checks = new[] { httpCheck };
            agentServiceRegistration.ID = config.GatewayAddress;
            agentServiceRegistration.Name = config.ServiceName;
            agentServiceRegistration.Address = config.GatewayAddress.Split(":")[1].Split("//")[1];
            agentServiceRegistration.Port = Convert.ToInt32(config.GatewayAddress.Split(":")[2].Split("/")[0]);
            agentServiceRegistration.Meta = new Dictionary<string, string>() { { "Weight", config.Weight.HasValue ? config.Weight.Value.ToString() : "1" } };
            agentServiceRegistration.Tags = new[] { $"urlprefix-/{config.ServiceName}" };
            _consulClient.Agent.ServiceRegister(agentServiceRegistration).Wait();
            timer = new Timer();
            timer.Interval = TimeSpan.FromMinutes(2).TotalMilliseconds;
            timer.Elapsed += TimerRegisterService;
            timer.Start();
        }
        public void TimerRegisterService(object sender, ElapsedEventArgs e)
        {
            _consulClient.Agent.ServiceRegister(agentServiceRegistration).Wait();
        }

    }
}
